﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using MySite.Enum;
using System.IO;
using MySite.Helper;
using System.Xml;
using MySite.Model;
using MySite.BLL;

namespace MySite.Timer
{
    public class BlogcnTimer : ITimer
    {
        public string blogCNURL = System.Configuration.ConfigurationManager.AppSettings["BlogcnURL"];

        public static IList<BlogInfo> biList = new List<BlogInfo>();

        public override void GlobalTimer_ToDo(object state)
        {
            biList.Clear();
            string result = new HttpRequestHelper().HttpRequestGet(blogCNURL);

            XmlHelper xml = new XmlHelper();
            xml.XmlHelperInitByXMLString(result);

            XmlNodeList xnl =  xml.Read("entry");

            foreach (XmlElement xn in xnl)
            {

                BlogInfo bi = new BlogInfo();
                XmlNode author = xn.GetElementsByTagName("author")[0];
                if (author.HasChildNodes)
                {
                    bi.Author_Name = author["name"].InnerText;
                    bi.Author_URL = author["uri"].InnerText;
                }
                bi.Content = xn.GetElementsByTagName("content")[0].InnerText.Replace("'", "\"");
                bi.OriginalID = xn.GetElementsByTagName("id")[0].InnerText;
                bi.OriginalURL = xn.GetElementsByTagName("id")[0].InnerText;
                bi.PublishTime = Convert.ToDateTime(xn.GetElementsByTagName("published")[0].InnerText);
                bi.Title = xn.GetElementsByTagName("title")[0].InnerText.Replace("'", "\"");
                bi.Summary = xn.GetElementsByTagName("summary")[0].InnerText.Replace("'", "\"");
                bi.Type = BlogType.Blogcn;
                biList.Add(bi);
                
            }
            new Blog().Delete(string.Format(" DateDiff('d',PublishTime,Date())>0"));
            new Blog().UpdateBlog(biList);
        }
    }
}
